<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket调试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            border-bottom: 3px solid #667eea;
            padding-bottom: 10px;
        }
        .status {
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
            font-weight: bold;
        }
        .status.disconnected {
            background: #fee;
            color: #c00;
        }
        .status.connected {
            background: #efe;
            color: #060;
        }
        button {
            padding: 12px 24px;
            margin: 5px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
        }
        .btn-connect {
            background: #667eea;
            color: white;
        }
        .btn-disconnect {
            background: #ef4444;
            color: white;
        }
        .btn-test {
            background: #10b981;
            color: white;
        }
        #log {
            background: #1e1e1e;
            color: #d4d4d4;
            padding: 20px;
            border-radius: 5px;
            height: 400px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.6;
            margin-top: 20px;
        }
        .log-info { color: #4ec9b0; }
        .log-success { color: #6a9955; font-weight: bold; }
        .log-error { color: #f48771; font-weight: bold; }
        .log-warning { color: #dcdcaa; }
        .log-message { color: #ce9178; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 WebSocket调试工具</h1>
        
        <div id="status" class="status disconnected">
            ❌ 未连接
        </div>

        <div>
            <button class="btn-connect" onclick="connect()">🔌 连接WebSocket</button>
            <button class="btn-disconnect" onclick="disconnect()">❌ 断开连接</button>
            <button class="btn-test" onclick="triggerCheck()">🚀 触发预警检查</button>
            <button class="btn-disconnect" onclick="clearWarnings()">🗑️ 清除所有预警</button>
        </div>

        <div id="log"></div>
    </div>

    <script>
        let ws = null;
        let messageCount = 0;
        let authToken = null;

        // 获取Token（从URL参数或localStorage）
        function getToken() {
            // 1. 尝试从URL参数获取token
            const urlParams = new URLSearchParams(window.location.search);
            const urlToken = urlParams.get('token');
            if (urlToken) {
                localStorage.setItem('token', urlToken);
                return urlToken;
            }
            
            // 2. 从localStorage获取token
            const storedToken = localStorage.getItem('token');
            if (storedToken) {
                return storedToken;
            }
            
            return null;
        }

        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const time = new Date().toLocaleTimeString();
            const className = 'log-' + type;
            logDiv.innerHTML += `<div class="${className}">[${time}] ${message}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }

        function updateStatus(connected) {
            const statusDiv = document.getElementById('status');
            if (connected) {
                statusDiv.className = 'status connected';
                statusDiv.textContent = '✅ 已连接';
            } else {
                statusDiv.className = 'status disconnected';
                statusDiv.textContent = '❌ 未连接';
            }
        }

        function connect() {
            log('=== 开始连接WebSocket ===', 'info');
            
            const wsUrl = 'ws://localhost:8086/ws/warning';
            log('连接地址: ' + wsUrl, 'info');

            try {
                ws = new WebSocket(wsUrl);
                log('WebSocket对象已创建', 'info');

                ws.onopen = function(event) {
                    log('✅ WebSocket连接成功！', 'success');
                    updateStatus(true);
                    log('连接事件详情: ' + JSON.stringify({
                        readyState: ws.readyState,
                        protocol: ws.protocol,
                        url: ws.url
                    }), 'info');
                };

                ws.onmessage = function(event) {
                    messageCount++;
                    log('📨 收到消息 #' + messageCount, 'success');
                    log('原始数据: ' + event.data, 'message');
                    
                    try {
                        const data = JSON.parse(event.data);
                        log('解析后的JSON:', 'info');
                        log(JSON.stringify(data, null, 2), 'message');
                        
                        if (data.type === 'connect') {
                            log('✅ 服务器确认连接 - SessionId: ' + data.sessionId, 'success');
                        } else if (data.type === 'new_warning') {
                            log('🚨 收到新预警！', 'warning');
                            log('预警编号: ' + data.warningNo, 'warning');
                            log('预警标题: ' + data.warningTitle, 'warning');
                            log('预警级别: ' + data.warningLevel, 'warning');
                            log('预警内容: ' + data.warningContent, 'warning');
                        } else if (data.type === 'clear_warnings') {
                            log('🗑️ 收到清除预警通知！', 'success');
                            log('消息: ' + data.message, 'success');
                            log('清除时间: ' + data.clearedTime, 'info');
                            log('所有预警已清除，预警列表已重置', 'success');
                        }
                    } catch (e) {
                        log('❌ 解析消息失败: ' + e.message, 'error');
                    }
                };

                ws.onerror = function(error) {
                    log('❌ WebSocket错误!', 'error');
                    log('错误详情: ' + JSON.stringify(error), 'error');
                    updateStatus(false);
                };

                ws.onclose = function(event) {
                    log('🔌 WebSocket连接已关闭', 'warning');
                    log('关闭代码: ' + event.code, 'info');
                    log('关闭原因: ' + event.reason, 'info');
                    log('是否正常关闭: ' + event.wasClean, 'info');
                    updateStatus(false);
                };

            } catch (e) {
                log('❌ 创建WebSocket时出错: ' + e.message, 'error');
                log('错误堆栈: ' + e.stack, 'error');
            }
        }

        function disconnect() {
            if (ws) {
                log('=== 主动断开连接 ===', 'warning');
                ws.close();
                ws = null;
            } else {
                log('当前未连接', 'info');
            }
        }

        function triggerCheck() {
            log('=== 触发预警检查 ===', 'info');
            
            fetch('/api/warning/check', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + authToken,
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 401) {
                    log('❌ 未登录或Token已过期', 'error');
                    log('请重新登录后再访问此页面', 'error');
                } else {
                    log('✅ 预警检查API调用成功', 'success');
                    log('响应: ' + JSON.stringify(data), 'message');
                    log('请等待WebSocket推送消息...', 'info');
                }
            })
            .catch(error => {
                log('❌ 预警检查API调用失败: ' + error.message, 'error');
            });
        }

        function clearWarnings() {
            if (!confirm('确定要清除所有预警吗？此操作将删除数据库中的所有预警记录！')) {
                log('取消清除操作', 'info');
                return;
            }
            
            log('=== 清除所有预警 ===', 'warning');
            
            fetch('/api/warning/clear', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + authToken,
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 401) {
                    log('❌ 未登录或Token已过期', 'error');
                    log('请重新登录后再访问此页面', 'error');
                } else {
                    log('✅ 清除预警API调用成功', 'success');
                    log('响应: ' + JSON.stringify(data), 'message');
                    log('数据库预警已清除，等待WebSocket通知...', 'info');
                }
            })
            .catch(error => {
                log('❌ 清除预警API调用失败: ' + error.message, 'error');
            });
        }

        window.onload = function() {
            log('=== WebSocket调试工具已加载 ===', 'info');
            
            // 获取并验证Token
            authToken = getToken();
            if (!authToken) {
                log('❌ 未找到登录Token', 'error');
                log('请先登录系统，然后访问此页面', 'error');
                log('或者使用URL参数传递token: ws-debug.html?token=YOUR_TOKEN', 'error');
                return;
            }
            
            log('✅ 已获取登录Token', 'success');
            log('Token前缀: ' + authToken.substring(0, 20) + '...', 'info');
            log('===============================', 'info');
            
            log('功能说明:', 'info');
            log('1️⃣ 连接WebSocket - 建立实时通信连接', 'info');
            log('2️⃣ 触发预警检查 - 检查并生成预警，通过WebSocket推送', 'info');
            log('3️⃣ 清除所有预警 - 清空数据库预警，通过WebSocket通知', 'info');
            log('4️⃣ 断开连接 - 关闭WebSocket连接', 'info');
            log('===============================', 'info');
            log('测试流程建议:', 'info');
            log('步骤1: 点击"连接WebSocket"', 'info');
            log('步骤2: 点击"触发预警检查"观察预警生成', 'info');
            log('步骤3: 点击"清除所有预警"观察清除通知', 'info');
            log('步骤4: 再次触发预警检查，观察新预警生成', 'info');
            log('===============================', 'info');
        };
    </script>
</body>
</html>

